package com.example.onlinemallsystem.service.impl;


import com.example.onlinemallsystem.entity.Category;
import com.example.onlinemallsystem.mapper.CategoryMapper;
import com.example.onlinemallsystem.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    //查询所有商品分类
    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.selectAll();
    }
    //根据id查询商品分类
    @Override
    public Category getCategoryById(Long id) {
        return categoryMapper.selectById(id);
    }
    //根据父类id查询商品分类
    @Override
    public List<Category> getCategoriesByParentId(Long parentId) {
        return categoryMapper.selectByParentId(parentId);
    }

    //添加商品分类
    @Override
    @Transactional
    public Long addCategory(Category category) {
        // 设置默认值
        if (category.getSort() == null) {
            category.setSort(0);
        }
        if (category.getStatus() == null) {
            category.setStatus(1);
        }
        if (category.getDeleted() == null) {
            category.setDeleted(0);
        }

        categoryMapper.insert(category);
        return category.getId();
    }

    //更新商品分类
    @Override
    @Transactional
    public boolean updateCategory(Category category) {
        int rows = categoryMapper.update(category);
        return rows > 0;
    }

    //根据id删除商品分类
    @Override
    @Transactional
    public boolean deleteCategory(Long id) {
        // 检查是否有子分类
        List<Category> children = getCategoriesByParentId(id);
        if (children != null && !children.isEmpty()) {
            throw new RuntimeException("该分类下存在子分类，无法删除");
        }

        int rows = categoryMapper.deleteById(id);
        return rows > 0;
    }

    @Override
    public int insertCategory(Category category) {
        return categoryMapper.insert(category);
    }
}

